package com.junzhiit.nengji.api.interceptor;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class AccessControlAllowOriginInterceptor extends HandlerInterceptorAdapter {

	protected Log logger = LogFactory.getLog(this.getClass().getName());
	
	@Value("${sys.accessControlAllowOrigin}")
	private String accessControlAllowOrigin;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		logger.debug("Access Control Allow Origin:" + accessControlAllowOrigin);
		
		Set<String> allowedOrigins= new HashSet<String>(Arrays.asList(accessControlAllowOrigin.split(","))); 
		String originHeader=request.getHeader("Origin");
		if(allowedOrigins.contains(originHeader)){
			response.setHeader("Access-Control-Allow-Origin", originHeader);
			response.setHeader("Access-Control-Allow-Methods", "*");
			response.setHeader("Access-Control-Allow-Headers", "content-type");
			response.setHeader("Access-Control-Allow-Credentials", "true");
		}
		
		logger.debug("AccessControlAllowOriginInterceptor run.....");
		return true;
	}

}
